package cn.highedu.coolsharkhub.controller;

import cn.highedu.coolsharkhub.pojo.dto.UserLoginDTO;
import cn.highedu.coolsharkhub.pojo.vo.UserVO;
import cn.highedu.coolsharkhub.service.UserService;
import cn.highedu.coolsharkhub.service.exception.EntityNotFoundException;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * @author HighEDU
 */
@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * 如果登录成功，返回用户登录结果
     * @param userDTO 用户信息数据传输对象
     * @return 登录结果
     */
    @PostMapping("/users/login")
    public String login(@RequestBody UserLoginDTO userDTO, HttpSession session){
        logger.info("userDTO: {}", userDTO);
        String username = userDTO.username();
        String password = userDTO.password();
        //调用业务方法
        UserVO userVO = userService.login(username, password);
        //将用户信息存入session
        session.setAttribute("user", userVO);
        return "登录成功";
    }

    /**
     * 用户退出
     * @param session
     * @return
     */
    @GetMapping("/users/logout")
    public String logout(HttpSession session){
        //清除session
        session.invalidate();
        return "退出成功";
    }

    /**
     * 获取当前用户名
     */
    @GetMapping("/users/current")
    public String getCurrentUsername(HttpSession session){
        //从session中获取用户信息
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null){
            //如果用户信息为空，返回没有登录
            return "没有登录";
        }
        return userVO.username();
    }

    // 以下是Rest 测试代码：
    /**
     * 测试方法
     * {id} 表示一个占位符
     */
    @GetMapping("/users/{id}")
    public UserVO getUserById(@PathVariable("id") Integer userId) { // @PathVariable表示接收请求URL中占位符里的参数
        // 测试
        logger.info("测试数据 id: {}", userId);
        return new UserVO(1, "admin", "123456", "ADMIN");
    }

    @GetMapping("/users/{id}/name")
    public String getUserName(@PathVariable("id") Integer userId){
        //测试
        logger.info("userId: {}", userId);
        return "Tom";
    }

    @DeleteMapping("/users/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT) // 返回的状态码是 204
    public String deleteUser(@PathVariable Integer id) {
        logger.info("测试数据 id: {}", id);
        return "删除成功";
    }

    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND) // 返回的状态码是 404
    public String handleEntityNotFoundException(EntityNotFoundException e){
        return e.getMessage();
    }

}
